import json
import logging
import traceback
from datetime import datetime
from django.db import transaction
from django.http import JsonResponse
from rest_framework import status
from Model.models import Community as C
from Model.modelsView import CommunityInfo
from tools.Tools import check_text, getCurrentUser, createHandleLog

logger_info = logging.getLogger('info')
res = dict()


def Community(request):
    res.clear()
    try:
        if request.method == 'GET':
            return queryCommunity(request)
        elif request.method == 'POST':
            return createCommunity(request)
        elif request.method == 'PUT':
            return modifyCommunity(request)
        elif request.method == 'DELETE':
            return delCommunity(request)
    except Exception as e:
        print(e)
        logger_info.error(f'当前接口：{request.path} 异常，异常内容为:{traceback.format_exc()}')
        res['status'] = 200
        res['message'] = '请求错误!'
        return JsonResponse(res, status=status.HTTP_400_BAD_REQUEST)


# 获取园区信息
def queryCommunity(request):
    current = request.GET.get('current')
    pageSize = request.GET.get('pageSize')
    name = request.GET.get('name')
    district_id = request.GET.get('district_id')
    subdistrict_id = request.GET.get('subdistrict_id')
    community = CommunityInfo.objects.all()
    if check_text(name):
        community = community.objectsfilter(name__contains=name)
    if check_text(district_id):
        community = community.filter(district_id=district_id)
    if check_text(subdistrict_id):
        community = community.filter(subdistrict_id=subdistrict_id)
    total = community.count()
    dataJson = list(
        community.values()[int(pageSize) * int(current) - int(pageSize):int(pageSize) * int(current)])
    res['status'] = 200
    res['data'] = dataJson
    res['total'] = total
    res['message'] = '请求成功'
    return JsonResponse(res, status=status.HTTP_200_OK)


# 新建园区
@transaction.atomic
def createCommunity(request):
    body = json.loads(request.body)
    name = body.get('name')
    district_id = body.get('district_id')
    subdistrict_id = body.get('subdistrict_id')
    community = C.objects.create()
    community.community_id = community.id
    community.subdistrict_id = subdistrict_id
    community.district_id = district_id
    community.name = name
    createHandleLog('新增园区', str(getCurrentUser(request)), body)
    logger_info.info(f'{getCurrentUser(request)} 在 {str(datetime.now())[:19]} 操作《新增园区》权限 新增内容 {body}')
    community.save()
    res['status'] = 200
    res['message'] = '新建成功'
    return JsonResponse(res, status=status.HTTP_200_OK)


# 修改园区
@transaction.atomic
def modifyCommunity(request):
    body = json.loads(request.body)
    community_id = body.get('community_id')
    name = body.get('name')
    district_id = body.get('district_id')
    subdistrict_id = body.get('subdistrict_id')
    community = C.objects.get(community_id=community_id)
    community.name = name
    community.district_id = district_id
    community.subdistrict_id = subdistrict_id
    createHandleLog('修改园区', str(getCurrentUser(request)), body)
    logger_info.info(f'{getCurrentUser(request)} 在 {str(datetime.now())[:19]} 操作《修改园区》权限 新增内容 {body}')
    community.save()
    res['status'] = 200
    res['message'] = '修改成功'
    return JsonResponse(res, status=status.HTTP_200_OK)


# 删除园区
@transaction.atomic
def delCommunity(request):
    community_id = request.GET.get('community_id')
    community = C.objects.get(community_id=community_id)
    createHandleLog('删除园区', str(getCurrentUser(request)), community.name)
    logger_info.info(f'{getCurrentUser(request)} 在 {str(datetime.now())[:19]} 操作《删除园区》权限 删除 {community.name}')
    community.delete()
    res['status'] = 200
    res['message'] = '删除成功'
    return JsonResponse(res, status=status.HTTP_200_OK)
